package com.gpframework.module.controller.ctn;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.utils.aliySms.AliySmsUtils;
import com.gpframework.common.utils.aliySms.SmsReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author ZS
 * @version 1.0
 * @date 2024/1/10 16:39
 */

@Slf4j
@RestController
@Api(tags = "登录相关")
@RequestMapping("/login")
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SendSmsController {

    private final RedisCache redisCache;

    /**
     * 发送注册短信
     * @param smsReq
     * @return
     */
    @ApiOperation(value = "发送短信")
    @PostMapping("/sendSms")
    public AjaxResult sendSms(@RequestBody SmsReq smsReq) throws ClientException {
        if (com.gpframework.common.utils.StringUtils.isBlank(smsReq.getPhone())) {
            return AjaxResult.error("请填写手机号");
        }
        smsReq.setAreaCode("+86"); // 区号默认国内
        String randomCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        SendSmsResponse res = AliySmsUtils.sendSms(smsReq.getPhone(), randomCode, smsReq.getAreaCode());
        if ("OK".equals(res.getCode())) {
            // 将短信信息写入缓存中
            String key = UUID.randomUUID().toString();
            redisCache.setCacheObject(key, randomCode);
            redisCache.expire(key, 3);
            return AjaxResult.success(key);
        } else {
            return AjaxResult.error("发送失败，请稍后重试");
        }
    }



}
